package jsp;

import entity.Dept;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:石小俊
 * @Date:2022/12/14 9:03
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@WebServlet("/showAddEms")
public class ShowAddEmpAndDeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有部门信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Dept> depts = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" select id,name,remark ")
                    .append(" from t_dept ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                Dept dept = new Dept();
                dept.setId(rs.getInt("id"));
                dept.setName(rs.getString("name"));
                dept.setRemark(rs.getString("remark"));
                depts.add(dept);
            }
            request.setAttribute("depts",depts);
            request.getRequestDispatcher("/jsp/addEmp.jsp").forward(request,response);

            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
